import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter_list_view/flutter_list_view.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:sticky_headers/sticky_headers.dart';

import '../../../login/page/user_manager.dart';
import '../../../net/api/http_api.dart';
import '../../../net/response/food/single_menu_data.dart';
import '../../../net/response/food/site_list_data.dart';
import '../../../res/colors.dart';
import '../../../ui/food/apply_select_food_page.dart';
import '../../../ui/food/new_single/new_apply_select_food_page.dart';
import '../../../util/image_utils.dart';

class NewSingleMenuViewModel extends BaseListViewModel<SingleMenuData> {
  final String? date;
  final SiteListData site;
  final String? orderType;
  final PickerDataWithIdModel? foodTime;
  final int? useNumber;
  final PickerDataWithIdModel? userWay;
  final int? humanOldId;

  NewSingleMenuViewModel(BuildContext context,
      {this.date,
      this.orderType,
      required this.site,
      this.foodTime,
      this.useNumber,
      this.userWay,this.humanOldId})
      : super(context);

  @override
  Future<List<SingleMenuData>> requestListData() async {
    var map = await PostRequest.singleFoodMenu(site!.id.toString());
    var list = ((map['data'] as List) ?? [])
        .map((e) => SingleMenuData.fromJson(e))
        .toList();
    selectedType = list[0];
    return list;
  }

  @override
  void onCreated() {
    super.onCreated();
    requestRefresh();
  }

  SingleMenuData? selectedType;

  Widget menuTypeWidget() {
    return FlutterListView.builder(
      itemBuilder: (context, index) {
        var item = listItems[index];
        var count = item.selectCount;
        return Stack(
          alignment: Alignment.center,
          fit: StackFit.expand,
          children: [
            CommonText(item.name).addToContainer(alignment: Alignment.center),
            count == 0
                ? Container()
                : CommonText(count.toString(),
                        textColor: Colors.white, textSize: 14)
                    .addToContainer(
                        decoration: BoxDecoration(
                            shape: BoxShape.circle, color: Colors.red),
                        width: 16,
                        height: 16,
                        alignment: Alignment.center)
                    .setLocation(right: 0, top: 4)
          ],
        )
            .addToContainer(
              width: double.infinity,
              height: 50,
              decoration: BoxDecoration(
                  color: selectedType == item ? Colors.white : Colours.bg_color,
                  borderRadius: selectedType != item
                      ? index == 0
                          ? BorderRadius.only(bottomRight: 10.radius)
                          : index == listItems.length - 1
                              ? BorderRadius.only(topRight: 10.radius)
                              : 10.borderRadius
                      : 0.borderRadius),
              alignment: Alignment.center,
            )
            .addToContainer(color: Colors.white)
            .onTap(() {
          selectedType = item;
          notifyListeners();
        });
      },
      itemCount: listItems.length,
    );
  }

  ///菜单content
  Widget foodMenuWidget() {
    var typeData = (selectedType?.goodsInfoList??[]).toTypeData();
    print(typeData.length);
    return ListView.builder(
      cacheExtent: 1,
      itemBuilder: (context, index) {
        var item = typeData[index];
        return StickyHeader(
            header: CommonText(item.typeName).addToContainer(
                color: Colors.white,
                width: double.infinity,
                height: 40,
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(
                  horizontal: 10,
                )),
            content: ListView(
              shrinkWrap: true,
              physics: NeverScrollableScrollPhysics(),
              children: item.foodList.map((e) {
                return Stack(
                  children: [
                    (e.attachIds.isNullOrEmpty()
                            ? ImageLoad(
                                ImageUtils.getImgPath('none'),
                                width: 70,
                                height: 70,
                                isAsset: true,
                              )
                            : ImageLoad(
                                '${HttpApi.imageHead}${e.attachIds}',
                                width: 70,
                                height: 70,
                                fit: BoxFit.cover,
                                header: {"Cookie":UserManager.cookieStr},
                                errorImage: ImageUtils.getImgPath('none'),
                                placeholder: ImageUtils.getImgPath('none'),
                              ))
                        .toRound(borderRadius: 4.borderRadius),
                    Column(
                      children: [
                        CommonText(e.goodsName),
                        Container(),
                      ],
                    ).setLocation(left: 80, top: 5),
                    CommonText('¥${e.price}',
                            textSize: 14, textColor: Colors.red)
                        .setLocation(left: 80, bottom: 0),
                    Row(
                      children: [
                        e.number == 0
                            ? Container()
                            : Icon(
                                Icons.remove_circle_outline,
                                color: Colours.app_main,
                              ).onTap(() {
                                if (e.number <= 0) {
                                  return;
                                }
                                e.number--;
                                notifyListeners();
                              }),
                        e.number == 0
                            ? Container()
                            : CommonText(e.number.toString()).addToContainer(
                                margin: EdgeInsets.symmetric(horizontal: 14)),
                        Icon(
                          Icons.add_circle_outline_rounded,
                          color: Colours.app_main,
                        ).onTap(() {
                          e.number++;
                          notifyListeners();
                        }),
                      ],
                    ).setLocation(right: 0, bottom: 0)
                  ],
                ).addToContainer(
                    color: Colors.white,
                    height: 90,
                    padding:
                        EdgeInsets.symmetric(horizontal: 10, vertical: 10));
              }).toList(),
            ));
      },
      itemCount: typeData.length,
    ).addToContainer(color: Colors.white);
  }

  Widget bottomWidget() {
    var totalPrice = getTotalPrice();
    return Row(
      children: [
        Container(
          width: 16,
        ),
        CommonText('价格：', textSize: 16, fontWeight: FontWeight.bold),
        CommonText('¥$totalPrice',
            textColor: Colors.red, textSize: 17, fontWeight: FontWeight.bold),
        Container().setWeight(1),
        TextButton(
          onPressed: () {
            var goods = getSelectFood();
            if (goods.isEmpty) {
              showToast('请先选择菜品');
              return;
            }
            Go().push(NewApplySelectFoodPage(
              date: date??"",
              site: site,
              orderType: orderType??"",
              foodTime: foodTime!,
              useNumber: useNumber!,
              selectFood: goods,
              totalPrice: totalPrice,userWay: userWay!,humanOldId: humanOldId!,));
          },
          child: CommonText(
            '去下单',
            textColor: Colors.white,
          ),
          style: ButtonStyle(
              backgroundColor: WidgetStateProperty.all(Colours.app_main),
              shape: WidgetStateProperty.all(RoundedRectangleBorder()),
              minimumSize:
              WidgetStateProperty.all(Size(140, double.infinity))),
        )
      ],
    ).addToContainer(height: 60, color: Colors.white);
  }

  num getTotalPrice() {
    num price = 0;
    for (var item in listItems) {
      price += item.selectPrice;
    }
    return price;
  }

  List<SingleGoodsInfoList> getSelectFood() {
    var list = <SingleGoodsInfoList>[];
    for (var item in listItems) {
      list.addAll(item.selectFoodList);
    }
    return list;
  }
}
